package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type User struct {
	ID           uint
	Name         string
	Email        *string
	Age          uint8
	Birthday     *time.Time
	MemberNumber sql.NullString
	ActivatedAt  sql.NullTime
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func main() {
	dsn := "root:root@tcp(192.168.1.11:3306)/gorm_test?charset=utf8mb4&parseTime=True&loc=Local"

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			Colorful:                  true,        // Disable color
		},
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}

	//var user User
	var users []User
	//SELECT * FROM `users` WHERE id = 22 ORDER BY `users`.`id` LIMIT 1
	//db.First(&user, "id = ?", 22)

	//Plain SQL
	//db.Find(&user, "name = ?", "james")
	//fmt.Println(user)

	//	db.Find(&users, "name <> ? AND age > ?", "john", 0)
	//SELECT * FROM `users` WHERE name <> 'john' AND age > 0

	//Struct

	//db.Find(&users, User{Age: 0})
	//SELECT * FROM `users`

	db.Find(&users, map[string]interface{}{"age": 0})
	//SELECT * FROM `users` WHERE `age` = 0
	for _, u := range users {
		fmt.Println(u.Name)
	}
}
